package com.jiangwz.springbootjwt.inteceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.jiangwz.springbootjwt.util.JwtUtils;

import io.jsonwebtoken.Claims;

/**
 * @author jiangwz
 * @create 2019/10/24.
 */
@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private JwtUtils jwt;
    public static final String USER_KEY = "userId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (request.getRequestURI().contains("/login")) return true;
        //获取用户凭证
        String token = request.getHeader(jwt.getHeader());
        if(StringUtils.isBlank(token)){
            token = request.getParameter(jwt.getHeader());
        }
        //凭证为空
        if(StringUtils.isBlank(token)){
            throw new Exception(jwt.getHeader() + "不能为空");
    }

        Claims claims = jwt.getClaimByToken(token);
        if(claims == null || jwt.isTokenExpired(claims.getExpiration())){
            throw new Exception(jwt.getHeader() + "失效，请重新登录");
        }

        //设置userId到request里，后续根据userId，获取用户信息
        request.setAttribute(USER_KEY, Long.parseLong(claims.getSubject()));

        return true;
    }
}
